/* eslint-disable no-param-reassign */
/* eslint-disable react/sort-comp */
import React from 'react';
import { View } from '@tarojs/components';

import './index.<%= css %>';

interface IShowModal {
  renderContent?: React.ReactNode;
}

class ShowModal extends React.Component<IShowModal> {
  success = () => {};

  cancel = () => {};

  donotClose = false;

  state = {
    visible: false,
    title: '提示',
    cancelText: '取消',
    confirmText: '确认',
    showCancel: true,
    content: '',
    height: '100vh',
  };

  handleClose = (e) => {
    e.stopPropagation();
    this.cancel && this.cancel();
    this.setState({
      visible: !!this.donotClose,
    });
  };

  handleCloseButton = (e) => {
    e.stopPropagation();
    this.cancel && this.cancel();
    this.setState({
      visible: false,
    });
  };

  handleConfirm = async (e) => {
    e.stopPropagation();
    try {
      this.success && (await this.success());
    } finally {
      this.setState({
        visible: false,
      });
    }
  };

  showModal = (options) => {
    this.success = options.success;
    this.cancel = options.cancel;
    // 是否阻止关闭
    this.donotClose = options.donotClose || false;

    delete options.success;
    delete options.cancel;
    delete options.donotClose;

    this.setState({
      visible: true,
      ...options,
    });
  };

  render() {
    const preventTouchMove = () => {};
    const { visible, title, cancelText, content, confirmText, showCancel, height } = this.state;
    const { renderContent } = this.props;

    return (
      <View
        style={{ height }}
        catchMove
        // @ts-ignore
        catchtouchmove={preventTouchMove}
        className={visible ? 'modal-cover-view' : 'hidden-cover-view'}
      >
        <View className="modal-mask" onClick={this.handleClose} />
        <View className="modal-container" onClick={(e) => e.stopPropagation()}>
          <View className="modal-title">{title}</View>
          <View className="modal-content">{content || renderContent}</View>
          <View className="modal-action">
            {showCancel ? (
              <View onClick={this.handleCloseButton} className="cancel-button button">
                {cancelText}
              </View>
            ) : null}
            <View onClick={this.handleConfirm} className="button">
              {confirmText}
            </View>
          </View>
        </View>
      </View>
    );
  }
}

export default ShowModal;
